package com.hut.oa.controller;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpSession;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.hut.oa.model.bean.Attachment;
import com.hut.oa.model.bean.Dept;
import com.hut.oa.model.bean.DeptOffice;
import com.hut.oa.model.bean.Role;
import com.hut.oa.model.bean.User;
import com.hut.oa.model.dao.AttachmentDao;
import com.hut.oa.model.dao.role.RoleDao;
import com.hut.oa.model.dao.user.DeptDao;
import com.hut.oa.model.dao.user.DeptOfficeDao;
import com.hut.oa.model.dao.user.UserDao;
import com.hut.oa.service.AttachmentService;
import com.hut.oa.service.UserService;

@Controller
@RequestMapping("/user")
public class UserController {
	Logger log=LoggerFactory.getLogger(getClass());
	SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
	
	@Autowired
	DeptDao dd;
	
	@Autowired
	DeptOfficeDao dod;
	
	@Autowired
	UserDao ud;
	
	@Autowired
	RoleDao rd;
	
	@Autowired
	UserService us;
	
	@Autowired
	AttachmentDao ad;
	
	@Autowired
	AttachmentService as;
	
	/**
	 * 到用户面板界面
	 * @return
	 */
	@RequestMapping
	public String userPlan(){
		return "user_panel";
	}
	
	/**
	 * 修改系统设置
	 */
	@RequestMapping(value="/system/update",method=RequestMethod.POST)
	@ResponseBody
	public void systemUpdate(String name,String password,String newPassword,String skin,Long id){
		if(newPassword!=null && newPassword!=""){
			password=newPassword;
		}
		us.updateSystem(name, password, skin, id);
	}
	
	/**
	 * 修改基本信息
	 * @throws ParseException 
	 */
	@RequestMapping(value="/base/update",method=RequestMethod.POST)
	@ResponseBody
	public void baseUpdate(HttpSession session,String tel,@RequestParam(name="birDay")String birDay,String address,String bank,String email) throws ParseException{
		User me=(User) session.getAttribute("userinfo");
		Date birday=format.parse(birDay);
		System.out.println("111111111111111111");
		us.updateBase(me.getId(), tel, birday, address, bank, email);
		System.out.println("222222222222222222");
	}
	
	
	/**
	 * 到部门列表页面
	 * @return
	 */
	@RequestMapping("/dept")
	public String toDept(Model model,String key,@PageableDefault(value=10,sort={"grade"}) Pageable pageable){
		Page<Dept> page;
		if(key!=null && key!=""){
			log.info("关键字查询： {}", key);
			page=dd.findByNameLOrTelOrEmail(key,pageable);
		}else{
			page=dd.findAll(pageable);
		}
		model.addAttribute("dept", page);
		return "user/dept";
	}
	
	/**
	 * 修改部门信息页面
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping("/dept/getone")
	public String getDept(Long id,Model model){
		model.addAttribute("dept", dd.findById(id));
		return "user/editDept";
	}
	
	/**
	 * 到添加部门页面
	 * @return
	 */
	@RequestMapping(value="/dept/add",method=RequestMethod.GET)
	public String addDept(){
		return "user/editDept";
	}
	
	/**
	 * 部门表单数据提交
	 * @return
	 */
	@RequestMapping(value="/dept/edit",method=RequestMethod.POST)
	@ResponseBody
	public Dept saveDeptData(Dept dept){
		if(dept.getId()!=null){
			log.info("修改部门");
		}else{
			log.info("添加部门");
		}
		log.info("部门信息： {}",dd.save(dept));
		return dept;
	}
	
	/**
	 * 交换层级
	 * @param thisId
	 * @param otherId
	 */
	@RequestMapping("/dept/updategrade")
	@ResponseBody
	public void updateGrade(Long thisId,Long otherId){
		us.updateGrade(thisId, otherId);
		log.info("更改部门层级");
	}
	
	/**
	 * 删除单个部门
	 * @param id
	 */
	@RequestMapping("/dept/delete")
	@ResponseBody
	public void deleteDept(Long id){
		dd.delete(id);
		log.info("删除部门信息：id= {}",id);
	}
	
	/**
	 * 获取指定部门的职位
	 * @param id
	 * @param model
	 */
	@RequestMapping("/dept/office")
	public String findDeptOffice(Long id,Model model){
		model.addAttribute("directOffice", us.getOffice(dd.findById(id)));//直接下属
		System.out.println(id);
		System.out.println(us.getOffice(dd.findById(id)));
		return "user/office";
	}
	
	/**
	 * 到添加职位页面
	 * @return
	 */
	@RequestMapping(value="/dept/office/add",method=RequestMethod.GET)
	public String addDeptOffice(Long id,Model model){
		model.addAttribute("offices", dod.findByDept(dd.findById(id)));//获取该部门的所有职位
		model.addAttribute("depts", dd.findAllByOrderByGrade());//获取所有部门
		return "user/editOffice";
	}
	
	/**
	 * 获取所有部门
	 * @return
	 */
	@RequestMapping("/depts/get")
	@ResponseBody
	public List<Dept> getDepts(){
		return dd.findAllByOrderByGrade();
	}
	
	/**
	 * 根据部门获取职位
	 * @param id
	 * @return
	 */
	@RequestMapping("/dept/office/get")
	@ResponseBody
	public List<DeptOffice> getOffice(@RequestParam("id")Long id){
		return dod.findByDept(dd.findById(id));
	}
	
	/**
	 * 修改职位信息页面
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping("/dept/office/getone")
	public String getOffice(Long id,Long officeid,Model model){
		model.addAttribute("office", dod.findById(officeid));
		model.addAttribute("offices", dod.findByDept(dd.findById(id)));//获取该部门的所有职位
		model.addAttribute("depts", dd.findAllByOrderByGrade());//获取所有部门
		return "user/editOffice";
	}
	
	/**
	 * 到职位表单提交
	 * @return
	 */
	@RequestMapping(value="/dept/office/edit",method=RequestMethod.POST)
	@ResponseBody
	public DeptOffice saveOfficeData(Long id,DeptOffice deptOffice){
		if(deptOffice.getId()!=null){
			log.info("修改职位");
		}else{
			log.info("添加职位");
		}
		//System.out.println(deptOffice.getLeader());
		log.info("职位信息： {}",dod.save(deptOffice));
		return deptOffice;
	}
	
	/**
	 * 删除单个职位
	 * @param id
	 */
	@RequestMapping("/dept/office/delete")
	@ResponseBody
	public void deleteOffice(Long id){
		dod.delete(id);
		log.info("删除职位信息：id= {}",id);
	}
	
	
	
	
	
	
	
	
	/**
	 * 到用户列表页面
	 * @return
	 */
	@RequestMapping("/user")
	public String toUser(Model model,@RequestParam(value="deptId",required=false)Long deptId,@RequestParam(value="deptId",required=false)String key,@PageableDefault(value=10,sort={"hiredate"}) Pageable pageable){
		
		model.addAttribute("depts", dd.findAllByOrderByGrade());//获取所有部门
		
		model.addAttribute("users", us.findByContition(deptId, key, pageable));
		return "user/user";
	}
	
	/**
	 * 查看用户详情
	 * @return
	 */
	@RequestMapping("/user/info")
	public String toUserInfo(Model model,Long id){
		model.addAttribute("user", ud.findById(id));
		return "user/showUser";
	}
	
	/**
	 * 更改帐号密码
	 * @param accountName
	 * @param accountPwd
	 * @param userId
	 * @return
	 */
	@RequestMapping(value="/user/update",method=RequestMethod.POST)
	@ResponseBody
	public void updateAccount(String name,String pwd,Long userId){
		us.updateAccount(name, pwd, userId);
	}
	
	/**
	 * 到添加用户页面
	 * @return
	 */
	@RequestMapping("/user/add")
	public String toAddUser(Long id,Model model){
		User user=ud.findById(id);
		if(user!=null){
			model.addAttribute("user",user);
			model.addAttribute("office", dod.findByDept(user.getDept()));
		}
		model.addAttribute("roles", rd.findAll());
		model.addAttribute("dept", dd.findAllByOrderByGrade());
		return "user/editUser";
	}
	
	/**
	 * 查找用户名是否重复
	 * @param name
	 * @return
	 */
	@RequestMapping("/user/findname")
	@ResponseBody
	public boolean isHasName(String name){
		if(ud.findByName(name)!=null){
			return true;
		}
		return false;
	}
	
	/**
	 * 删除单个用户
	 * @param id
	 */
	@RequestMapping("/user/delete")
	@ResponseBody
	public void deleteUser(Long id){
		ud.delete(id);
		log.info("删除用户：id= {}",id);
	}
	
	/**
	 * 保存用户信息
	 * @param user
	 * @return
	 * @throws IOException 
	 * @throws IllegalStateException 
	 */
	@RequestMapping(value="/user/edit",method=RequestMethod.POST)
	@ResponseBody
	public User saveUserData(@RequestParam(value="file",required=false)MultipartFile file,User user) throws IllegalStateException, IOException{
		if(user.getId()!=null){
			log.info("修改用户");
		}else{
			log.info("添加用户");
		}
		//保存其他信息
		user=ud.save(user);
		if(file.getSize()>0){
			//保存头像
			Attachment att=as.saveAttachment(file, user.getId(), "head");
			att.setBusinessId(user.getId());//添加附件业务id
			att=ad.save(att);
			log.info("附件添加： {}",att);
			user.setPhoto(att.getPath());
			user=ud.save(user);
		}
		log.info("用户信息： {}",user);
		return user;
	}
	
	/**
	 * 获取所有用户
	 * @return
	 */
	@RequestMapping("/getusers")
	@ResponseBody
	public List<User> getUsers(HttpSession session){
		User user=(User) session.getAttribute("userinfo");
		return ud.findByIdNot(user.getId());
	}
}
